<template>
    <div class="clockSharing">
        <MaskItem :imgPercentage="imgPercentage"></MaskItem>
        <div class="container">
            <div class="crop-demo-btn">
                小程序打卡分享图
                <input class="crop-input" type="file" multiple name="wxImage" ref="wxImage" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadClockImg($event, 1)"/>
            </div>
            <div class="clockSharingList">
                <div class="clockSharingCell" v-for="(wxItem, wxIndex) in wxImageList" :key="'wx_'+wxIndex" :style="{backgroundImage:`url(${wxItem})`}">
                <!-- <div class="clockSharingCell" v-for="(itemTask, indexTask) in 5" :key="'task_'+indexTask" style="background: #999"> -->
                    <div class="cellBtn">
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteClockImage(wxIndex, 1)"></el-button>
                    </div>
                </div>
            </div>
            <!-- <el-row v-if="JSON.stringify(wxImageList) !== '[]'">
                <el-col :span="24">
                    <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="submit()">保存发布</el-button>
                </el-col>
            </el-row> -->
            <!-- <img :src="entrance_image" class="pic-img"> -->
        </div>

        <div class="container" style="margin-top: 20px;">
            <div class="crop-demo-btn">
                APP打卡分享图
                <input class="crop-input" type="file" multiple name="appImage" ref="appImage" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadClockImg($event, 2)"/>
            </div>
            <div class="clockSharingList">
                <div class="clockSharingCell" v-for="(appItem, appIndex) in appImageList" :key="'app_'+appIndex" :style="{backgroundImage:`url(${appItem})`}">
                <!-- <div class="clockSharingCell" v-for="(itemTask, indexTask) in 5" :key="'task_'+indexTask" style="background: #999"> -->
                    <div class="cellBtn">
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteClockImage(appIndex, 2)"></el-button>
                    </div>
                </div>
            </div>
            <!-- <el-row v-if="JSON.stringify(appImageList) !== '[]'">
                <el-col :span="24">
                    <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="submit()">保存发布</el-button>
                </el-col>
            </el-row> -->
            <!-- <img :src="entrance_image" class="pic-img"> -->
        </div>

        <el-row>
            <el-col :span="24">
                <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="submit()">保存发布</el-button>
            </el-col>
        </el-row>








        <!-- <div class="container" style="margin-top: 20px;">
            <div class="crop-demo-btn">选择app入口图片
                <input class="crop-input" type="file" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 3)"/>
            </div>
            <img :src="entrance_app_image" class="pic-img">
        </div>
        <div class="container" style="margin-top: 20px;">
            <div class="crop-demo-btn">选择介绍图片
                <input class="crop-input" type="file" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 2)"/>
            </div>
            <img :src="introduce_image" class="pic-img">
        </div>
        <el-row>
            <el-col :span="24">
                <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="submit()">保存发布</el-button>
            </el-col>
        </el-row> -->
    </div>
</template>

<script type="text/ecmascript-6">
    // import {baiduCloud} from '@/config/env'
    import { upLoadFileToOSS } from '@/config/utils'
    import {obtainClockSharing, updateClockSharing} from '@/config/api'

    import Mask from '../../common/mask.vue'
    export default {
        components: {
            MaskItem: Mask
        },
        data () {
            return {
                // // 百度云
                // akBos: baiduCloud.akBos,
                // skBos: baiduCloud.skBos,
                // endpointBos: baiduCloud.endpointBos,
                // bucketImgBos: baiduCloud.bucketBos +'/course/clock/image',
                // urlImgBos: baiduCloud.urlBos+'/course/clock/image/',
                // 图片上传进度
                imgPercentage: 0,

                // // 入口图片
                // entrance_image:  '',
                // // app入口图片
                // entrance_app_image:  '',
                // // 介绍图片
                // introduce_image: '',

                
                // 小程序打卡分享
                wxImageList: [],
                // app打卡分享
                appImageList: [],
                // 打卡分享状态 1 -- 小程序  2 -- app
                clockShareState: 0
            }
        },
        async mounted () {
            // // 初始化百度云上传
            // this.initBaiDuBce();
            // 获取原始图片
            await this.indexInfo();
        },
        methods: {
            // 获取数据
            async indexInfo () {
                let self = this;
                const clockInfo = await obtainClockSharing();
                if (clockInfo.status === 200) {
                    // 小程序打卡分享
                    self.wxImageList = JSON.parse(clockInfo.data.wx_image_list) || []
                    // app打卡分享
                    self.appImageList = JSON.parse(clockInfo.data.app_image_list) || []
                }
                // this.entrance_image = data.entrance_image ? data.entrance_image : [];
                // this.entrance_app_image = data.entrance_app_image ? data.entrance_app_image : [];
                console.log(clockInfo, self.wxImageList, self.appImageList, '获取成功')
            },
            // 提交
            async submit () {
                let self = this;
                console.log(self.wxImageList, '提交')
                if (JSON.stringify(self.wxImageList) === '[]' && JSON.stringify(self.appImageList) === '[]') {
                    this.$message({
                        message: '请上传入口图片',
                        type: 'warning'
                    });
                    return
                }
                // if (!this.entrance_image) {
                //     this.$message({
                //         message: '请上传入口图片',
                //         type: 'warning'
                //     });
                // }
                // if (!this.entrance_app_image) {
                //     this.$message({
                //         message: '请上app传入口图片',
                //         type: 'warning'
                //     });
                // }
                // if (!this.introduce_image) {
                //     this.$message({
                //         message: '请上传介绍图片',
                //         type: 'warning'
                //     });
                // };
                // if (JSON.stringify(self.wxImageList) === '[]') {
                //     self.wxImageList = ''
                // }
                // if (JSON.stringify(self.appImageList) === '[]') {
                //     self.appImageList = ''
                // }
                await updateClockSharing(JSON.stringify(self.wxImageList), JSON.stringify(self.appImageList))
                    .then(res => {
                        console.log(res)
                        if ( res.status === 200) {
                            this.$message({
                                message: '发布成功',
                                type: 'success'
                            });
                        } else {
                            this.$message.error('失败');
                        }
                    }).catch(err => {
                        console.error('错误信息',err)
                    });
            },
            // 删除打卡图片
            deleteClockImage(index, status) {
                let self = this;
                // 打卡分享状态 1 -- 小程序  2 -- app
                if (status === 1) {
                    // 小程序打卡分享
                    self.wxImageList.splice(index, 1);
                }
                if (status === 2) {
                    // app打卡分享
                    self.appImageList.splice(index, 1);
                }
            },
            // // 初始化百度云上传
            // initBaiDuBce(){
            //     let self = this;
            //     let bosConfig = {
            //         credentials: {
            //             ak: self.akBos,
            //             sk: self.skBos
            //         },
            //         endpoint: self.endpointBos  // 根据您选用bos服务的区域配置相应的endpoint
            //     };
            //     // let bucket = self.bucketBos; // 设置您想要操作的bucket
            //     self.client = new baidubce.sdk.BosClient(bosConfig);
            // },
            // 上传打卡图片
            async uploadClockImg(event, status){
                let self = this;
                // 打卡分享状态 1 -- 小程序  2 -- app
                self.clockShareState = status
                // 浏览器兼容 (FF不兼容event.srcElement)
                let evt = event.srcElement ? event.srcElement : event.target;
                // 获取要上传的文件
                let file = evt.files;
                // 阿里oss上传路径
                let ossPath = ''
                if (self.clockShareState === 1 || self.clockShareState === 2) {
                    ossPath = 'wx_bs/clock/image'
                }
                if (ossPath) {
                    const loading = self.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    for (let i = 0; i < file.length; i++) {
                        // // 上传图片
                        // self.uploadImg(file[i], i)
                        // 用户取消上传
                        if(file[i] == undefined){
                            return;
                        }
                        // 上传多媒体
                        const mainBannerUrl = await upLoadFileToOSS(file[i], ossPath)
                        console.log(mainBannerUrl, '选择欲上传的多媒体文件')
                        if (self.clockShareState === 1) {
                            self.wxImageList.push(mainBannerUrl)
                        }
                        if (self.clockShareState === 2) {
                            self.appImageList.push(mainBannerUrl)
                        }
                        if (i === file.length - 1) {
                            if (self.uploadStatus === 1) {
                                self.$refs.wxImage.value = ''
                            }
                            if (self.uploadStatus === 2) {
                                self.$refs.appImage.value = ''
                            }
                            loading.close()
                        }
                    }
                }
            },
            // // 上传图片
            // uploadImg(file, index){
            //     let self = this;
            //     // 用户取消上传
            //     if(file == undefined){
            //         return;
            //     }
            //     // 生成6位随机数
            //     let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
            //     let res = "";
            //     for(let i = 0; i < 6 ; i ++) {
            //         let id = Math.ceil(Math.random()*61);
            //         res += chars[id];
            //     }
            //     let key = res + '.' +file.name.split(/\./g).pop(); // 保存到bos时的key，您可更改，默认以文件名作为key
            //     let blob = file;
            //     let ext = key.split(/\./g).pop();
            //     let mimeType = baidubce.sdk.MimeType.guess(ext);
            //     if (/^text\//.test(mimeType)) {
            //         mimeType += '; charset=UTF-8';
            //     }
            //     let options = {
            //         'Content-Type': mimeType
            //     };
            //     self.client.putObjectFromBlob(self.bucketImgBos, key, blob, options)
            //         .then(function (res) {
            //             // 上传完成，添加您的代码
            //             console.log(key,res,'上传成功');
            //             // // banner
            //             // if (self.uploadStatus === 1  ) {
            //             //     self.entrance_image = self.urlImgBos + key;
            //             // };
            //             // // 课程介绍图
            //             // if (self.uploadStatus === 2 ) {
            //             //     self.introduce_image = self.urlImgBos + key;
            //             // };
            //             // // app banner
            //             // if (self.uploadStatus === 3  ) {
            //             //     self.entrance_app_image = self.urlImgBos + key;
            //             // };
            //             // 打卡分享状态 1 -- 小程序  2 -- app
            //             if (self.clockShareState === 1) {
            //                 self.$refs.wxImage.value = ''
            //                 self.wxImageList.push(self.urlImgBos + key)
            //             }
            //             if (self.clockShareState === 2) {
            //                 self.$refs.wxImage.value = ''
            //                 self.appImageList.push(self.urlImgBos + key)
            //             }
                        
            //             console.log('图片上传成功:',self.urlImgBos + key)
            //         })
            //         .catch(function (err) {
            //             // 上传失败，添加您的代码
            //             console.log(err);
            //         });

            //     self.client.on('progress', function (evt){
            //         // console.log(evt, ".....")
            //         // 监听上传进度
            //         if (evt.lengthComputable){
            //             self.imgPercentage = parseInt((evt.loaded / evt.total) * 100)+'';
            //             console.log(self.imgPercentage, "上传图片")
            //             self.imgPercentage = String(self.imgPercentage)
            //             // 满了，清空进度条
            //             if(self.imgPercentage == 100){
            //                 self.imgPercentage = 0
            //             }
            //         }
            //     });
            // },
        }
    }
</script>

<style lang="less" scoped>
    .clockSharing{
        .label-bannaer {
            display: inline-block;
        }
        #bannaer {
            opacity: 0;
            display: block;
            width: 100%;
            height: 100%;
        }
        .crop-demo-btn{
            position: relative;
            width: 160px;
            height: 40px;
            line-height: 40px;
            padding: 0 20px;
            background-color: #409eff;
            color: #fff;
            font-size: 14px;
            border-radius: 4px;
            box-sizing: border-box;
            text-align: center;
            display: inline-block;
        }
        .crop-input{
            position: absolute;
            width: 150px;
            height: 40px;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        .pic-img {
            width: 50%;
            margin-top: 25px;
        }
    }
</style>
<style lang="less" scoped>
  @import 'ClockSharing.less';
</style>
